package com.jams.goodox.activity.login;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.entity.LoginBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.SecureUtils;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.EditTextWithDel;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";
    @Bind(R.id.edit_userPass)
    EditTextWithDel editUserPass;
    @Bind(R.id.edit_userName)
    EditTextWithDel editUserName;
    @Bind(R.id.img_login_seePass)
    ImageView img_login_seePass;

    private static final String USER_ERROR = "账号密码错误";
    private static final String USER_PASSWORD_ERROR = "请输入密码";
    private static final String USER_NAME_ERROR = "请输入账号";

    private boolean isPassShow = false;//标示密码是否可见
    private Intent in;

    private String userName;

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "登录");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
//        setTitleVisibility(false);
//        StatusBarCompat.transStatusBar(this);
        Utils.setFilter(editUserPass);//设置编辑框过滤器

        editUserName.requestFocus();
        //旧手机号码存入啦
//        String pl= SePref.getPrePhone();
//        if(!TextUtils.isEmpty(pl)){
//            editUserName.setText(pl);
//            editUserName.setSelection(editUserName.length());
//        }
        //添加一个下一步点击监听事件
        editUserPass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if(actionId== EditorInfo.IME_ACTION_DONE){
                    login();
                }
                return false;
            }
        });
    }

    @OnClick({R.id.text_login_index, R.id.tx_register, R.id.tx_forgot_password, R.id.img_login_seePass})
    public void onClick(View view) {
        if (Utils.isFastDoubleClick())
            return;
        switch (view.getId()) {
            case R.id.text_login_index://点击登录
                login();

                break;
            case R.id.tx_register:
                in = new Intent(this, GetCodeActivity.class);//获取短信验证码
                in.putExtra("from",0);//注册时的获取验证码
                startActivity(in);
                break;
            case R.id.tx_forgot_password:
                in = new Intent(this, GetCodeActivity.class);
                in.putExtra("from",1);//修改密码时的获取验证码
                startActivity(in);
                break;
            case R.id.img_login_seePass:
                isPassShow = !isPassShow;
                if (isPassShow) {
                    img_login_seePass.setImageResource(R.mipmap.see_pass_icon);
                    editUserPass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    img_login_seePass.setImageResource(R.mipmap.not_see_pass_icon);
                    editUserPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                editUserPass.setSelection(editUserPass.length());
                break;
        }
    }


    /**
     * 登录
     */
    private void login() {
        userName = editUserName.getText().toString();
        String userPass = editUserPass.getText().toString();


        if (!Utils.isPhoneNum(userName)) {
            ToastUtil.show( "请输入正确的手机号");
            return;
        }

        if (TextUtils.isEmpty(userPass)) {
            ToastUtil.show("请输入密码");
            return;
        }

        if (userName.length() < 8 || userPass.length() < 6) {
            ToastUtil.show(USER_ERROR);
            return;
        }
        String md5Pwd = SecureUtils.getMD5(userPass);


        clearMap();
        StringBuilder pData = new StringBuilder();
        pData.append("mobile:" + userName)
                .append(",password:" + userPass);
//
//        params.put("requestData", "{" + pData.toString() + "}");
//
//        String strEntity = gson.toJson(params);
//        RequestBody body = RequestBody.create(MediaType.parse("application/json"), strEntity);
//
//        ProtocolManagers.getRequestMap("{" + pData.toString() + "}");
        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).login(ProtocolManagers.getRequestMap("{" + pData.toString() + "}"));
        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        misLoading();
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));

                        //存信息入配置文件:仅登录信息
//                        SePref.putToken("test");
                        SePref.setId(object.getInt("id"));

                        SePref.setPrePhone(userName);//保存手机号

                        if(object.has("certPic")){
                            SePref.setHeadImageUrl(object.getString("certPic"));
                        }

                        if(object.has("memberType")){
                            //判断用户 有没有memberType
                            SePref.putToken("test");
                            int memberType = object.getInt("memberType");
                            SePref.setMemberType(memberType);
                            SePref.setNickName(object.getString("nickName"));

                            if(memberType == 1){
                                SePref.putGrade(object.getString("grade"));
                                if(object.has("city")){
                                    SePref.setCity(object.getString("city"));
                                }
                            }

                            if(memberType == 2){
                                SePref.putIndividualitySign(object.getString("individualitySign"));
                            }

                            ToastUtil.show("登录成功");

                            startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                            finish();
                        }else {
                            startActivity(new Intent(LoginActivity.this,RoleChooseActivity.class));
                            finish();
                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }

                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

    }

    /**
     * 保存用户信息&跳转下个页面
     * @param loginData 接口返回数据
     */
    private void saveUser(LoginBean.LoginBeanData loginData) {

        //判断用户账号性质，企业账号进入企业账号首页，个人账号进入个人账号首页
        boolean isCompanyAccount= User.USER_TYPE_COMPANY.equalsIgnoreCase(loginData.getUserType());
        DataCacheManager.getInstance().setUser(loginData.transform());

        //存信息入配置文件:仅登录信息
//        SePref.putUserId(loginData.getUserId());
        SePref.putToken(loginData.getToken());
        SePref.putUserPhone(loginData.getMobileNum());
        SePref.putCommunityName(loginData.getUserName());
        SePref.putAlisa(loginData.getAlias());
        SePref.putUserPhone(userName);//此处用于退出登录后，编辑框显示的历史账号信息
        SePref.putCommunityId(loginData.getCommunityId());


        /*if(isCompanyAccount){
            in = new Intent(LoginActivity.this, EnterPriseHomeActivity.class);
        }else {
            in = new Intent(LoginActivity.this, HomeActivity.class);
        }*/

        in = new Intent(LoginActivity.this, HomeActivity.class);
        startActivity(in);
        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!TextUtils.isEmpty(SePref.getToken())) {//注册完成，返回登录页，进入首页，用于情空中间页面
            in=new Intent(this, HomeActivity.class);
            startActivity(in);
            finish();
        }
    }
}
